package cn.bdqn.auth_consumer.service;

import cn.bdqn.common.Constants;
import cn.bdqn.common.MD5Utils;
import cn.bdqn.common.RedisUtils;
import cn.bdqn.mapper.UsersMapper;
import cn.bdqn.pojo.Users;
import cn.bdqn.service.SmsCodeService;
import cn.bdqn.service.TokenService;
import cn.bdqn.vo.RegisterVo;
import cn.bdqn.vo.TokenVo;
import cn.bdqn.vo.UsersVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import org.springframework.jms.annotation.JmsListener;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;

/**
 * 2018/9/20
 */
@Service
public class UserServiceImpl implements UserService {
    @Reference
    private TokenService tokenService;
    @Reference
    private SmsCodeService smsCodeService;

    @Resource
    private UsersMapper usersMapper;
    @Resource
    private RedisUtils redisUtils;

    /**
     * 用户登录
     *
     * @param phone
     * @param password
     * @return
     * @throws Exception
     */
    @Override
    public String login(String phone, String password) throws Exception {

        if (null == phone || phone.equals("")) {
            throw new Exception("手机号错误");
        }
        //数据库查询用户是否注册
        Users user = null;

        try {
            user = usersMapper.findByPhone(phone);
        } catch (Exception e) {
            throw new Exception("查询失败！");
        }
        if (null != user) {
            if (!MD5Utils.getMD5(password, 32).equals(user.getPassword())) {
                throw new Exception("密码错误");
            }
        } else {
            throw new Exception("您还没有注册 请先注册");
        }
        String token = tokenService.getToken(user);

        return token;
    }


    /**
     * 注册 发送短信
     *
     * @param pram
     * @throws Exception
     */
    @JmsListener(destination = Constants.MQ_PHONE_JSM)
    @Override
    public void sendRegisterEmail(String pram) throws Exception {
       UsersVo usersVo = JSON.parseObject(pram,UsersVo.class);
       String phone = usersVo.getPhone();
       String code = MD5Utils.createRandom();
        RegisterVo registerVo = new RegisterVo();
        registerVo.setPhone(phone);
        registerVo.setCode(code);
        //registerVo.setCreateTime(new Date().getTime());
        registerVo.setCreateTime(System.currentTimeMillis());
        //redis保存
        redisUtils.set(Constants.PHONE_PREFIX+phone,Constants.REGISTER_TIME,JSON.toJSONString(registerVo));
        //调用方法发送短信
        smsCodeService.smsCodeSend(phone,code);



    }


    /**
     * 判断用户是否注册
     *
     * @param phone
     * @return
     * @throws Exception
     */
    @Override
    public boolean userExist(String phone) throws Exception {
        Users users = usersMapper.findByPhone(phone);
        if (users != null) {
            return true;
        } else {
            throw new Exception("用户名不存在！");
        }
    }

    /**
     * 置换token
     * @param token
     * @return
     * @throws Exception
     */
    @Override
    public TokenVo reToken(String token) throws Exception {
        String newToken = null;
        try {
            newToken = tokenService.replacementToken(token);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

        return new TokenVo(newToken, Calendar.getInstance().getTimeInMillis()+ Constants.TOKEN_VALID_TIME,Calendar.getInstance().getTimeInMillis());

    }

    /**
     * 退出操作
     * @param token
     * @throws Exception
     */
    @Override
    public void logOut(String token) throws Exception {
        tokenService.logOut(token);

    }

    /**
     * 激活用户（insert）
     * @param userCode
     * @param value
     * @return
     * @throws Exception
     */
    @Override
    public boolean phoneActivate(String userCode, String value,UsersVo usersVo) throws Exception {
        String phone = (String) redisUtils.get(Constants.PHONE_PREFIX+userCode);
        if(phone != null){
            RegisterVo registerVo = JSON.parseObject(phone,RegisterVo.class);
            if(value.equals(registerVo.getCode())){
                //添加用户
                Users users = new Users();
                users.setPhone(usersVo.getPhone());
                //注册成功后默认密码为000000
                users.setPassword("000000");
                users.setCreationdate(new Date());
               usersMapper.insertSelective(users);
                redisUtils.delete(Constants.PHONE_PREFIX+userCode);
                return true;
            }
        }

        return false;
    }


}
